package com.joostschouten.common.service.catpcha;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Locale;

import javax.imageio.ImageIO;

import nl.windgazer.arachne.services.captcha.ImageCaptchaService;

import com.octo.captcha.service.CaptchaServiceException;

/**
 * Implementation of the CaptchaService Interface.
 * Class CaptchaServiceImp
 */
public class CaptchaServiceImp implements CaptchaService {
	
	public static final String BEAN_NAME = "captchaService";

    /**
     * 
     */
    private ImageCaptchaService imageCaptureService;

	private final Locale locale;

    /**
     * 
     * @param cs
     */
    public CaptchaServiceImp(final ImageCaptchaService cs, Locale locale) {
        this.imageCaptureService = cs;
        this.locale = locale;
    }

    /**
     * Creates a jpeg captcha images using {@link #imageCaptureService} and returns this as a byte array.
     * 
     * @param captchaId
     * @param locale
     * 
     * @return a byte array containing the jpeg captcha image
     * 
     * @throws IOException
     * @throws IllegalArgumentException
     * @throws CaptchaServiceException
     */
    public byte[] getCaptcha(final String captchaId, final Locale locale)
        throws IOException, IllegalArgumentException,
        CaptchaServiceException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            // call the ImageCaptchaService getChallenge method
            BufferedImage challenge = imageCaptureService.getImageChallengeForID(captchaId, locale);

            //Writing the image to outputstream
            ImageIO.write(challenge, "jpg", os);
            // flush it in the response
            os.flush();

            return os.toByteArray();
        }
        finally {
            if (os != null) {
                os.close();
            }
        }
    }

    /**
     * Validates the users input against the id of the captcha that was shown to them
     * 
     * @param captchaId
     * @param inputChars
     * 
     * @return true if <code>inputChars</code> matches the <code>captchaId</code>
     */
    public boolean validateCaptcha(final String captchaId, final String inputChars) {

        boolean bValidated = false;
        try {
            bValidated = imageCaptureService.validateResponseForID(captchaId,
                                                                   inputChars,
                                                                   locale);
        }
        catch (CaptchaServiceException cse) {
        }
        return bValidated;
    }

    /**
     * @return the imageCaptureService
     */
    public ImageCaptchaService getImageCaptureService() {
        return imageCaptureService;
    }

    /**
     * @param cs the imageCaptureService to set
     */
    public void setImageCaptureService(ImageCaptchaService cs) {
        this.imageCaptureService = cs;
    }
}

